﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using pygs.Classes;

namespace pygs.Messaging.Buffer
{
    class MemoryBuffer : CustomBuffer
    {
        private System.Object lockThis = new System.Object();

        private List<Message> _buffer;
        protected List<Message> buffer { get { return _buffer; } }

        protected override void InitilizeComponent()
        {
            base.InitilizeComponent();
            _buffer = new List<Message>();
        }

        public override void Add(Message message)
        {
            lock (lockThis)
            {
                buffer.Add(message);
            }
        }

        public override void Add(List<Message> list)
        {
            Add(list.AsEnumerable());
        }

        public override void Add(IEnumerable<Message> list)
        {
            lock (lockThis)
            {
                buffer.AddRange(list);
            }
        }

        public override void AddToTop(Message message)
        {
            lock (lockThis)
            {
                buffer.Insert(0, message);
            }
        }

        public override void AddToTop(List<Message> list)
        {
            AddToTop(list.AsEnumerable());
        }

        public override void AddToTop(IEnumerable<Message> list)
        {
            lock (lockThis)
            {
                buffer.InsertRange(0, list);
            }
        }

        private Message DoGetTop()
        {
            Message msg = null;
            if (buffer.Count != 0)
            {
                msg = buffer.First();
                buffer.RemoveAt(0);
            }
            return msg;
        }

        public override Message GetTop()
        {
            Message msg = null;
            lock (lockThis)
            {
                msg = DoGetTop();
            }
            return msg;
        }

        public override List<Message> GetTop(int count)
        {
            var list = new List<Message>();
            lock (lockThis)
            {
                for (int i = count; i > 0; i--)
                {
                    Message msg = DoGetTop();
                    if (msg == null)
                        break;
                    list.Add(msg);
                }
            }
            return list;
        }

        protected override int GetCount()
        {
            return buffer.Count;
        }
    }
}
